﻿$(document).ready(function () {
    $("#ProductTypeID").combobox('readonly', true);
    initGirdFront();
    initGirdDetail();
    $("#txtDetail").val("");    
    var productID = $("#hidProductID").val();
    initData(productID);    
});
var FileInput = function () {
    var oFile = new Object();
    //初始化fileinput控件（第一次初始化）
    oFile.Init = function (ctrlName, uploadUrl) {
        var control = $('#' + ctrlName)
        //初始化上传控件的样式
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: uploadUrl, //上传的地址
            allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
            showUpload: true, //是否显示上传按钮
            showCaption: false,//是否显示标题
            browseClass: "btn btn-primary", //按钮样式 
            dropZoneEnabled: true,//是否显示拖拽区域
            showPreview: true,
            maxFileCount: 1,
            enctype: 'multipart/form-data',
            validateInitialCount: true,
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        });
        //导入文件上传完成之后的事件
        $("#txt_file").on("fileuploaded", function (event, data, previewId, index) {
            $('#dgimgfront').datagrid('appendRow', {
                FileID: data.response.ID,
                SFileName: data.response.SFileName,
                LFileName: data.response.LFileName
            });
        });
    }
    return oFile;
};
var FileInput2 = function () {
    var oFile = new Object();
    //初始化fileinput控件（第一次初始化）
    oFile.Init = function (ctrlName, uploadUrl) {
        var control = $('#' + ctrlName)
        //初始化上传控件的样式
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: uploadUrl, //上传的地址
            allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
            showUpload: true, //是否显示上传按钮
            showCaption: false,//是否显示标题
            browseClass: "btn btn-primary", //按钮样式
            showPreview: true,
            maxFileCount: 5,
            enctype: 'multipart/form-data',
            validateInitialCount: true,
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        });
        //导入文件上传完成之后的事件
        $("#txt_file2").on("fileuploaded", function (event, data, previewId, index) {
            $('#dgimgdetail').datagrid('appendRow', {
                FileID: data.response.ID,
                SFileName: data.response.SFileName,
                LFileName: data.response.LFileName
            });
        });
    }
    return oFile;
};
CKEDITOR.replace('txtDetail', {
    width: 600,
    height: 500,
    toolbar: "Basic"
});
function initData(productID) {
    $.ajax({
        type: "get",
        url: "/ProductInfo/GetEditData?productID=" + productID,
        async: false,
        dataType: "json",
        error: function (ajaxExceptionModel) {
            //显示错误
            var obj = JSON.stringify(ajaxExceptionModel.responseText);
            alert(obj.messager);
        },
        success: function (result) {
            if (result != null && result != undefined && result.IsSuccess) {
                var productInfo = JSON.parse(result.Data);
                $('#ProductTypeID').combobox('setValue', productInfo.ProductTypeID);
                $('#Title').val(productInfo.Title);
                $('#Model').val(productInfo.Model);
                $('#Introduction').val(productInfo.Introduction);
                $('#Price').val(productInfo.Price);
                $("#txtDetail").val(productInfo.Detail);    
                $('#ContactUser').val(productInfo.ContactUser);
                $('#ContactPhone').val(productInfo.ContactPhone);
                var frontData = { total: 0, rows: [] };
                var detailData = { total: 0, rows: [] };
                for (var i = 0; i < productInfo.Files.length; i++) {
                    if (productInfo.Files[i].FileType == 1) {
                        frontData.total += 1;
                        frontData.rows.push(productInfo.Files[i]);
                    }
                    else if (productInfo.Files[i].FileType == 0) {
                        detailData.total += 1;
                        detailData.rows.push(productInfo.Files[i]);
                    }
                }
                $('#dgimgfront').datagrid('loadData', frontData);
                $('#dgimgdetail').datagrid('loadData', detailData);
            }            
        }
    })
}
function returngrid() {
    location.href = '/ProductInfo/ShowProductInfo';
}
function editfrontDel(index) {
    $.messager.confirm('提示', '是否删除', function (r) {
        if (r) {
            $('#dgimgfront').datagrid('deleteRow', index);
        }
    });
}
function editdetailDel(index) {
    $.messager.confirm('提示', '是否删除', function (r) {
        if (r) {
            $('#dgimgdetail').datagrid('deleteRow', index);
        }
    });
}
function initGirdFront() {
    $('#dgimgfront').datagrid({
        pagination: false,
        rownumbers: true,
        fitColumns: true,
        singleSelect: true,
        columns: [[
            {
                field: 'op', title: '操作', width: 50, align: 'center',
                formatter: function (value, row, index) {
                    var _frontstr = '<input type="button" class="btn btn-danger btn-xs" style="margin:3px;" onclick="addfrontDel(' + index + ')" value="删除">';
                    return _frontstr;
                }
            },
            {
                field: 'FileID', title: '文件ID', width: 60, align: 'center', hidden: true
            },
            {
                field: 'SFileName', title: '文件名', width: 160, align: 'center',
            },
            {
                field: 'LFileName', title: '长文件名', width: 60, align: 'center', hidden: true
            }
        ]]
    });
    var noData = { total: 0, rows: [] };
    $('#dgimgfront').datagrid('loadData', noData);
}
function initGirdDetail() {
    $('#dgimgdetail').datagrid({
        pagination: false,
        rownumbers: true,
        fitColumns: true,
        singleSelect: true,
        columns: [[
            {
                field: 'op', title: '操作', width: 50, align: 'center',
                formatter: function (value, row, index) {
                    var _detailstr = '<input type="button" class="btn btn-danger btn-xs" style="margin:3px;" onclick="adddetailDel(' + index + ')" value="删除">';
                    return _detailstr;
                }
            },
            {
                field: 'FileID', title: '文件ID', width: 60, align: 'center', hidden: true
            },
            {
                field: 'SFileName', title: '文件名', width: 160, align: 'center',
            },
            {
                field: 'LFileName', title: '长文件名', width: 60, align: 'center', hidden: true
            }
        ]]
    });
    var noData = { total: 0, rows: [] };
    $('#dgimgdetail').datagrid('loadData', noData);
}
function openUploadfront() {
    var rows = $('#dgimgfront').datagrid('getRows');
    if (rows.length == 0) {
        oFileInput = new FileInput();
        oFileInput.Init("txt_file", "/ProductInfo/UploadImage?type=0");
        $("#myModal").modal();
    } else {
        $.messager.alert('提示', '已存在1个图片，达到上限无法上传!');
    }
}
function openUploaddetail() {
    var rows = $('#dgimgdetail').datagrid('getRows');
    if (rows.length <= 5) {
        oFileInput2 = new FileInput2();
        oFileInput2.Init("txt_file2", "/ProductInfo/UploadImage?type=1");
        $("#myModal2").modal();
    } else {
        $.messager.alert('提示', '已存在5个图片，达到上限无法上传!');
    }
}

//修改方法
function editoka() {
    var param = {};
    param.productID = $('#hidProductID').val();
    param.ProductTypeID = $('#ProductTypeID').combobox("getValue");
    param.Title = $('#Title').val();
    param.Model = $('#Model').val();
    param.Introduction = $('#Introduction').val();
    param.Price = $('#Price').val();
    param.Detail = CKEDITOR.instances.txtDetail.getData();
    param.ContactUser = $('#ContactUser').val();
    param.ContactPhone = $('#ContactPhone').val();
    param.IsPublished = $('input[name=IsPublished]:checked').val();

    var detailrows = $('#dgimgdetail').datagrid('getRows');
    var files = [];
    for (var i = 0; i < detailrows.length; i++) {
        files.push({
            FileID: detailrows[i].FileID,
            SFileName: detailrows[i].SFileName,
            LFileName: detailrows[i].LFileName,
            FileType: 1
        })
    }
    var frontrows = $('#dgimgfront').datagrid('getRows');
    for (var i = 0; i < frontrows.length; i++) {
        files.push({
            FileID: frontrows[i].FileID,
            SFileName: frontrows[i].SFileName,
            LFileName: frontrows[i].LFileName,
            FileType: 0
        })
    }
    param.Files = files;
    if (param.producttypeid == "" || param.title == "" || param.model == "" || param.introduction == "" || param.price == "" || param.contactuser == "" || param.contactphone == "" || param.ispublished == "") {
        $.messager.alert('提示', '表单不能有空!');
        return;
    }
    $.ajax({
        type: "post",
        url: "/ProductInfo/EditSaveProductInfo",
        async: false,
        data: param,
        dataType: "json",
        error: function (ajaxExceptionModel) {
            //显示错误
            var obj = JSON.stringify(ajaxExceptionModel.responseText);
            alert(obj.messager);
        },
        success: function (result) {
            if (result != null && result != undefined && result.IsSuccess == true) {
                $.messager.alert('提示', '保存成功!');
                location.href = '/ProductInfo/ShowProductInfo';
            } else {
                $.messager.alert('提示', '保存失败，请重试!');
            }
             
        }
    })
    returngrid();
}